﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Faust.Andrew.MTG.Player
{
	/// <summary>
	/// Interaction logic for CardViewControl.xaml
	/// </summary>
	public partial class CardViewControl : UserControl, IPreviewView
	{
		public CardViewControl()
		{
			this.InitializeComponent();
		}
		
		static CardViewControl()
        {
            PresenterProperty = DependencyProperty.Register("Presenter", typeof(GamePresenter), typeof(CardViewControl));            
        }

        static DependencyProperty PresenterProperty;
        public GamePresenter Presenter
        {
            get
            {
                return (GamePresenter)base.GetValue(PresenterProperty);
            }
            set
            {
                base.SetValue(PresenterProperty, value);
            }
        }

        #region IPreviewView Members

        public void Preview(FrameworkElement element)
        {
            imgPreview.Source = CaptureScreenBitmap(element);
        }

        public void Preview(Shared.GameCard card)
        {
            DataContext = card;
            imgPreview.Source = Presenter.GetCardPreview(card);
            
            if (card.IsToken)
            {
                lblCardText.Content = card.ModifierText;
            }
            else
            {
                lblCardText.Content = String.Empty;
            }

            ToolTip = Presenter.GetCardTooltip(card);
        }
        #endregion

        private BitmapSource CaptureScreenBitmap(FrameworkElement target)
        {
            int width = (int)target.ActualWidth;
            int height = (int)target.ActualHeight;

            Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
            RenderTargetBitmap renderBitmap
            = new RenderTargetBitmap(width,
            height,
            96, 96,
            PixelFormats.Pbgra32);

            DrawingVisual visual = new DrawingVisual();
            using (DrawingContext context = visual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(target);
                context.DrawRectangle(brush,
                null,
                new Rect(new Point(), bounds.Size));
            }
            renderBitmap.Render(visual);
            return renderBitmap;
        }
	}
	
	
}